package customize

import (
	"fmt"
	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/model/cms"
	"gitcode.com/G-YT/baoyou/server/model/customize"
	"gitcode.com/G-YT/baoyou/server/model/user"
	"gorm.io/gorm"
	"strings"
	"time"
)

type HealthAnalyseService struct {
}

// SaveHealthReport 保存报告
func (healthAnalyseService *HealthAnalyseService) SaveHealthReport(record customize.HealthReport) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 生成唯一报告编号
		reportNumber := generateOrderCode("FD")
		//var userEfficacyTag assess.UserEfficacyTag
		var userInfo user.User
		// 脑波方案
		var nbDiseaseArticle []customize.DiseaseArticle // 未过滤ID
		bzIDs := strings.Split(record.DiseaseIDs, ",")
		// -------------------------------------------------------------获取病症关联脑波部分------------------------------------------------------------- //
		if nbDiseaseArticleErr := tx.Find(&nbDiseaseArticle, "disease_id in (?) and type = ?", bzIDs, "audio").Error; nbDiseaseArticleErr != nil {
			return nbDiseaseArticleErr
		}
		nbIDs := make([]uint, len(nbDiseaseArticle))
		for i, v := range nbDiseaseArticle {
			nbIDs[i] = v.ArticleID
		}
		var nbArticle []cms.Article
		//根据一级过滤
		if err = tx.Find(&nbArticle, "id in (?) and level_one_id = ?", nbIDs, 1).Error; err != nil {
			return err
		}
		nbaids := make([]uint, len(nbArticle))
		for i, v := range nbArticle {
			nbaids[i] = v.ID
		}
		// TODO 后续删掉，这里是默认给出的脑波文章
		//if len(nbaids) == 0 {
		//	nbaids = append(nbaids, []uint{2, 3, 4, 5, 6, 7}...)
		//}
		// 数组变字符串用","切割
		nbidsStr := strings.Join(strings.Split(fmt.Sprint(nbaids), " "), ",")
		// 运动方案
		var ydDiseaseArticle []customize.DiseaseArticle
		// -------------------------------------------------------------获取病症关联运动部分------------------------------------------------------------- //

		if err = tx.Find(&ydDiseaseArticle, "disease_id in (?) and type = ?", bzIDs, "video").Error; err != nil {
			return err
		}

		ydIds := make([]uint, len(ydDiseaseArticle))
		for i, v := range ydDiseaseArticle {
			ydIds[i] = v.ArticleID
		}
		//根据一级过滤
		var ydArticle []cms.Article
		if err = tx.Find(&ydArticle, "id in (?) and level_one_id = ?", ydIds, 2).Error; err != nil {
			return err
		}
		ydIDs := make([]uint, len(ydArticle))
		for i, v := range ydArticle {
			ydIDs[i] = v.ID
		}
		// TODO 后续删掉，这里是默认给出的运动文章
		//if len(ydaids) == 0 {
		//	ydaids = append(ydaids, []uint{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}...)
		//}
		// 数组变字符串用","切割
		ydIdsStr := strings.Join(strings.Split(fmt.Sprint(ydIDs), " "), ",")
		// -------------------------------------------------------------获取体质关联体质茶部分------------------------------------------------------------- //
		var tzCategory cms.Category
		//var tzName string
		//获取体质名称
		//err = tx.Table("fd_tz").First("id = ?", record.TzID).Pluck("tz_name", &tzName).Error
		var constitution customize.Constitution
		if err = global.GVA_DB.Model(&customize.Constitution{}).Where("id = ?", record.ConstitutionID).First(&constitution).Error; err != nil {
			return err
		}
		//获取体质levelTwoID
		if err = tx.First(&tzCategory, "`key` = ? AND category = 12", constitution.ID).Error; err != nil {
			return err
		}
		// 获取体质文章
		var tzArticle []cms.Article
		if tzArticleErr := tx.Find(&tzArticle, "category = ?", tzCategory.ID).Error; tzArticleErr != nil {
			return tzArticleErr
		}
		tzIds := make([]uint, len(tzArticle))
		for i, v := range tzArticle {
			tzIds[i] = v.ID
		}
		// 数组变字符串用","切割
		tzcIdsStr := strings.Join(strings.Split(fmt.Sprint(tzIds), " "), ",")
		// -------------------------------------------------------------获取功效&体质&节气&病症关联早午晚餐部分------------------------------------------------------------- //
		var pcIds []uint // 最终文章ids
		// ========================= 功效配餐 ========================= //
		// 查询用户功效ID
		if err = tx.First(&userInfo, "id = ?", record.Uid).Error; err != nil {
			return err
		}
		var EfficacyArticle []cms.Article // 功效文章 未过滤
		if err = tx.Find(&EfficacyArticle, "efficacy_id in (?) and type = ?", userInfo.EfficacyTagIDs, "graphic").Error; err != nil {
			return err
		}
		gxIds := make([]uint, len(EfficacyArticle))
		for i, v := range EfficacyArticle {
			gxIds[i] = v.ID
		}
		var gxArticle []cms.Article // 功效文章 过滤
		if err = tx.Find(&gxArticle, "id in (?) and category = ?", gxIds, 3).Error; err != nil {
			return err
		}
		for i := range gxArticle {
			pcIds = append(pcIds, gxArticle[i].ID)
		}
		// ========================= 节气配餐 ========================= //
		var solarTermsArticle []customize.SolarTermsArticle // 节气文章 未过滤
		err = tx.Find(&solarTermsArticle, "solar_terms_id in (?) and type = ?", record.SolarTermsID, "graphic").Error
		if err != nil {
			return err
		}
		solarTermsIds := make([]uint, len(solarTermsArticle))
		for i, v := range solarTermsArticle {
			solarTermsIds[i] = v.ArticleID
		}
		var solarTermsFilterArticle []cms.Article // 节气文章 过滤
		err = tx.Find(&solarTermsFilterArticle, "id in (?) and category = ?", solarTermsIds, 3).Error

		for i := range solarTermsFilterArticle {
			pcIds = append(pcIds, solarTermsFilterArticle[i].ID)
		}
		// ========================= 体质配餐 ========================= //

		var constitutionArticle []customize.ConstitutionArticle // 体质文章 未过滤
		err = tx.Find(&constitutionArticle, "constitution_id in (?) and type = ?", record.ConstitutionID, "graphic").Error
		if err != nil {
			return err
		}
		pcTzIds := make([]uint, len(constitutionArticle))
		for i, v := range constitutionArticle {
			pcTzIds[i] = v.ArticleID
		}
		var constitutionFilterArticle []cms.Article // 体质文章 过滤
		err = tx.Find(&constitutionFilterArticle, "id in (?) and category = ?", pcTzIds, 3).Error

		for i := range constitutionFilterArticle {
			pcIds = append(pcIds, constitutionFilterArticle[i].ID)
		}

		// ========================= 病症配餐 ========================= //

		var diseaseArticle []customize.DiseaseArticle // 病症文章 未过滤
		err = tx.Find(&diseaseArticle, "disease_id in (?) and type = ?", bzIDs, "graphic").Error
		if err != nil {
			return err
		}
		diseaseIds := make([]uint, len(diseaseArticle))
		for i, v := range diseaseArticle {
			diseaseIds[i] = v.ArticleID
		}

		var diseaseFilterArticle []cms.Article // 病症文章 过滤
		err = tx.Find(&diseaseFilterArticle, "id in (?) and category = ?", diseaseIds, 3).Error
		for i := range diseaseFilterArticle {
			pcIds = append(pcIds, diseaseFilterArticle[i].ID)
		}
		// TODO 后续删掉，这里是默认给出的配餐文章
		//if len(pcIds) == 0 {
		//	pcIds = append(pcIds, []uint{595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 649}...)
		//}
		// ============ 拼接 ================= 数组变字符串用","切割

		zwwcIdsStr := strings.Join(strings.Split(fmt.Sprint(pcIds), " "), ",")

		// 生成病症报告记录
		diseaseReportRecord := customize.HealthReport{
			Uid:            record.Uid,
			ReportNumber:   reportNumber,
			ConstitutionID: record.ConstitutionID,
			SolarTermsID:   record.SolarTermsID,
			DiseaseTypeIDs: record.DiseaseTypeIDs,
			DiseaseIDs:     record.DiseaseIDs,
		}
		if err := tx.Create(&diseaseReportRecord).Error; err != nil {
			return err
		}

		// 生成病症报告方案
		diseaseReportPlan := []customize.HealthPlan{
			{
				DrrID:       diseaseReportRecord.ID,
				ArticleType: 2,
				IDs:         nbidsStr,
				Types:       1,
			},
			{
				DrrID:       diseaseReportRecord.ID,
				ArticleType: 3,
				IDs:         ydIdsStr,
				Types:       2,
			},
			{
				DrrID:       diseaseReportRecord.ID,
				ArticleType: 1,
				IDs:         tzcIdsStr,
				Types:       3,
			},
			{
				DrrID:       diseaseReportRecord.ID,
				ArticleType: 1,
				IDs:         zwwcIdsStr,
				Types:       4,
			},
			{
				DrrID: diseaseReportRecord.ID,
				Types: 5,
			},
		}
		if err := tx.Create(&diseaseReportPlan).Error; err != nil {
			return err
		}
		return nil
	})
}

func generateOrderCode(prefix string) string {
	orderCode := prefix + getTime13()
	return orderCode
}

func getTime13() string {
	msec := time.Now().UnixNano() / int64(time.Millisecond)
	return fmt.Sprintf("%d", msec)[:13]
}
